#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <time.h>
#include <string.h>
#include <sys/time.h>
#define INTERVAL 200 

double get_time();
void print_usage();

double get_time()
{
    struct timeval tv;
    gettimeofday(&tv, NULL);
    return (tv.tv_sec * 1000 + tv.tv_usec * 1.0 / 1000);
}

void print_usage()
{
    printf("usage : kcpu -r 50 \n");
    printf("options : \n");
    printf(" -r specify cpu usage rate.\n");
    printf("\n");
}

int main(int argc, char *argv[])
{
    if (argc != 3) {
        printf("error : parameters error.\n");
        print_usage();
        exit(1);
    }

    int cpu_rate = 0; 
    if (strcmp(argv[1], "-r") == 0) {
        cpu_rate = atoi(argv[2]);
        if ((cpu_rate <= 0) || (cpu_rate > 100)) {
            printf("error : specify cpu usage rate error.\n");
            exit(1);
        }
    } else {
        printf("error : parameters error.\n");
        print_usage();
        exit(1);
    }

    double busy_span = INTERVAL * cpu_rate / 100; 
    double idle_span = INTERVAL * (100 - cpu_rate) / 100;

    double start_time; 

    while (1) {
        start_time = get_time();
        while ((get_time() - start_time) <= busy_span);
        usleep(idle_span * 1000);
    }
    return 0;
}